package com.cy.chatTest.interceptor;

import com.cy.chatTest.bin.BaseEntity;
import com.cy.chatTest.common.CommonUtil;
import com.cy.chatTest.common.StringUtils;
import com.cy.chatTest.db.UserInfo;
import com.cy.chatTest.db.UserInfoRepository;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class LoginInterceptor implements Filter {


    @Autowired
    UserInfoRepository userInfoRepository;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String url = httpServletRequest.getRequestURL().toString();
        if (httpServletRequest.getMethod().equals(GET)
                || url.contains("/register/")
                || url.contains("/headimg/")
                || url.contains("/login/login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        UserInfo userInfo = CommonUtil.getUserInfo(httpServletRequest,userInfoRepository);

        String cookie = CommonUtil.getCookie(httpServletRequest, "ChatApp");
        if (userInfo == null
                || userInfo.getCookie() == null
                || StringUtils.isEmpty(userInfo.getCookie())
                || !userInfo.getCookie().equals(cookie)
                || System.currentTimeMillis() > userInfo.getCookieValidity()
                ) {
            servletResponse.getWriter().write(new Gson().toJson(new BaseEntity(false, "cookie失效")));
            return;
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }

    }

    @Override
    public void destroy() {

    }
}
